<!-- //todo: 新建和编辑需要权限分开问题,111 初始化和锁定编辑功能 -->
<template>
  <el-dialog
    v-if="option.visible"
    v-drag="{ drag: drag }"
    :title="option.title"
    :visible.sync="option.visible"
    :close-on-click-modal="false"
    :width="option.width"
    :top="option.marginTop"
    :append-to-body="option.appendToBody"
    :class="{'dialogBox':option.isDialogBodyScroll}"
  >
    <el-form
      ref="validateForm"
      label-position="right"
      :label-width="widthLabel"
      :inline="inline"
      :model="formData"
    >
      <template v-for="(column, index) in columns" :key="column.id">
        <template v-if="column.slot">
          <!-- 有label，右侧slot -->
          <el-form-item
            v-if="column.label"
            :label="column.label"
          >
            <slot :name="column.slot" :tit="index" />
          </el-form-item>
          <!-- 否则全部slot -->
          <slot v-else :name="column.slot" :tit="index" />

        </template>
        <!---- switch -------->
        <el-form-item
          v-else-if="column.type ==='switch' "
          v-show="column.hide!==true"
          :label="column.label"
        >
          <el-switch v-model="formData[column.field]" :disabled="option.disabled ? column.disabled: false " @change="column.callback !== undefined? selectChange(formData[column.field],column.callback ,columns): ()=> {}" />
        </el-form-item>
        <!----  checkBoxGroup ----->
        <el-form-item
          v-else-if="column.type==='checkBoxGroup'"

          :label="column.label"
          :rules="column.rules"
          :prop="column.field"
        >
          <el-checkbox-group
            v-model="formData[column.field]"
            :disabled="option.disabled ? column.disabled: false "
          >
            <el-checkbox
              v-for="(item, i) in column.options"
              :key="i"
              :disabled="option.disabled ? column.disabled: false "
              :label="item"
            />
          </el-checkbox-group>
        </el-form-item>

        <!----  radioGroup ----->
        <el-form-item
          v-else-if="column.type==='radioGroup'"
          :key="index"
          :label="column.label"
          :rules="column.rules"
          :prop="column.field"
        >
          <!-- <el-checkbox-group v-model="formData[column.field]">
            <el-checkbox
              v-for="(item, i) in column.options"
              :key="i"
              :label="item"
            />
          </el-checkbox-group> -->
          <el-radio-group
            v-model="formData[column.field]"
            :disabled="option.disabled ? column.disabled: false "
          >
            <el-radio-button
              v-for="(item, i) in column.options"
              :key="i"
              :label="item.itemKey"
            >{{ item.itemValue }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <!-- ------------- select ------------------ -->
        <el-form-item
          v-else-if="column.type === 'select'"
          v-show="column.hide!==true"
          
          :label="column.label"
          :rules="column.rules"
          :prop="column.field"
        >
          <!-- 获取选中项的全部属性 -->
          <el-select
            v-if="column.valObj"
            v-model="formData[column.field]"
            :clearable="column.isClearable !== undefined ? column.isClearable : true"
            :style="[{width: '100%'},column.style]"
            :multiple="column.isMultiple"
            :placeholder="column.pre"
            value-key="id"
            :remote="column.remote"
            :loading="column.loading"
            :remote-method="column.remoteMethod"
            filterable
            :disabled="column.alwaysDisabled? true: option.disabled ? column.disabled: false"
            @change="column.callback !== undefined? selectChange(formData[column.field],column.callback ,columns): ()=> {}"
            @clear="column.callbackClearSelect !== undefined? clearSelect(formData[column.field],column.callbackClearSelect ,columns): ()=> {}"
          >
            <template v-if="column.isItemValue">
              <el-option
                v-for="item in column.options"
                :key="item.itemKey"
                :label="item.itemValue"
                :value="item.itemKey"
                :disabled="item.disabled"
              />
            </template>
            <template v-else>
              <el-option
                v-for="item in column.options"
                :key="item.id"
                :label="column.item === 'itemValue' ? item.itemValue : item.name"
                :value="item"
              />
            </template>
          </el-select>
          <el-select
            v-else
            v-model="formData[column.field]"
            :clearable="column.isClearable !== undefined ? column.isClearable : true"
            :style="[{width: '100%'},column.style]"
            :multiple="column.isMultiple"
            :loading="column.loading"
            :remote="column.remote"
            :remote-method="column.remoteMethod"
            :placeholder="column.pre"
            filterable
            :allow-create="column.allowCreate ? true : false"
            :default-first-option="column.allowCreate ? true: false"
            :disabled="column.alwaysDisabled? true: option.disabled ? column.disabled: false"
            @change="column.callback !== undefined? selectChange(formData[column.field],column.callback ,columns): ()=> {}"
            @clear="column.callbackClearSelect !== undefined? clearSelect(formData[column.field],column.callbackClearSelect ,columns): ()=> {}"
          >
            <template v-if="column.isItemValue">
              <el-option
                v-for="item in column.options"
                :key="item.itemKey"
                :label="item.itemValue"
                :value="item.itemKey"
                :disabled="item.disabled"
              />
            </template>
            <template v-else>
              <el-option
                v-for="item in column.options"
                :key="item.id"
                :label="column.item === 'itemValue' ? item.itemValue : item.name"
                :value="column.item === 'itemValue' ? item.itemKey : item.id"
              />
            </template>
          </el-select>
        </el-form-item>
        <!-- ------------- Cascader  ------------------ -->
        <el-form-item
          v-else-if="column.type === 'cascader'"
       
          :label="column.label"
          :rules="column.rules"
          :prop="column.field"
        >
          <el-cascader
            ref="myCascader"
            v-model="formData[column.field]"
            :style="[{width: '100%'},column.style]"
            :show-all-levels="column.isShowAllLevels"
            :options="column.options"
            :props="{ multiple: column.isMultiple, value: 'id', label: 'name', checkStrictly: column.checkStrictly,emitPath: false}"
            clearable
            :disabled="option.disabled ? column.disabled: false "
            @visible-change="visibleChange"
          />

        </el-form-item>

        <!-- -------------date------------------ -->
        <el-form-item
          v-else-if="column.type === 'date'"
          v-show="column.hide!==true"
      
          :label="column.label"
          :rules="column.rules"
          :prop="column.field"
        >

          <el-date-picker
            v-model="formData[column.field]"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="column.alwaysDisabled? true: option.disabled ? column.disabled: false"
            :placeholder="column.pre"
            :prop="column.field"
          />
        </el-form-item>
        <!-- -------------datetimerange------------------ -->
        <el-form-item
          v-else-if="column.type === 'datetimerange'"
        
          :label="column.label"
          :rules="column.rules"
          :prop="column.field"
        >
          <el-date-picker
            v-model="formData[column.field]"
            :disabled="column.alwaysDisabled? true: option.disabled ? column.disabled: false "
            :placeholder="column.pre"
            :prop="column.field"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>

        <!-- -------------datetimerange------------------ -->
        <el-form-item
          v-else-if="column.type === 'daterange'"
        
          :label="column.label"
          :rules="column.rules"
          :prop="column.field"
        >
          <el-date-picker
            v-model="formData[column.field]"
            :disabled="column.alwaysDisabled? true: option.disabled ? column.disabled: false "
            :placeholder="column.pre"
            :prop="column.field"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="column.pickerOptions || {}"
          />
        </el-form-item>
        <!-- ----------------------- -->
        <!-- -------------input-number------------------ -->
        <el-form-item
          v-else-if="column.type === 'inputNumber'"
          v-show="column.hide!==true"
       
          :label="column.label"
          :rules="column.rules"
          :prop="column.field"
        >
          <el-input-number
            v-model="formData[column.field]"
            :disabled="column.alwaysDisabled? true: option.disabled ? column.disabled: false "
            :placeholder="column.pre"
            :prop="column.field"
            :min="column.min"
            :max="column.max"
            :step="column.step"
            @change="column.callback !== undefined? selectChange(formData[column.field],column.callback ,columns): ()=> {}"
          />
        </el-form-item>
        <!-- -------------color-picker------------------ -->
        <el-form-item
          v-else-if="column.type === 'colorPicker'"
         
          :label="column.label"
          :prop="column.field"
        >
          <el-color-picker v-model="formData[column.field]" />
        </el-form-item>
        <!-- -------------uploadFile 上传组件------------------ -->
        <el-form-item
          v-show="column.hide!==true"
          v-else-if="column.type === 'uploadFile'"
        
          :ref="column.ref+'FormItem'"
          :rules="column.rules"
          :label="column.label"
          :prop="column.field"
        >
          <UploadFile :ref="column.ref" :options="column.options" />
          <!-- <el-color-picker v-model="formData[column.field]" /> -->
        </el-form-item>
        <!-- -------------input------------------ -->
        <el-form-item
          v-else
          v-show="column.hide!==true"
        
          :label="column.label"
          :rules="column.rules"
          :prop="column.field"
        >
          <!-- 验证信息 需要把column修改成 formData -->
          <template v-if="column.validForbid">
            <el-input
              v-model="formData[column.field]"
              :style="[{width: '100%'},column.style]"
              :placeholder="column.pre"
              :disabled="column.alwaysDisabled? true: option.disabled ? column.disabled: false "
              :prop="column.field"
              :type="column.type"
              autosize
              @input="e=>formData[column.field]=validForbid(e)"
            />

          </template>
          <template v-else>
            <el-input
              v-model="formData[column.field]"
              :style="column.clickInputCallback !== undefined?[{width: '100%'},column.style]:[{width: '100%'},column.style]"
              :placeholder="column.pre"
              :disabled="column.alwaysDisabled? true: option.disabled ? column.disabled: false "
              :prop="column.field"
              :type="column.type"
              autosize
              @click.native="column.clickInputCallback !== undefined? clickInputEvent(formData[column.field],column.clickInputCallback,columns,formData): ()=> {}"
              @change="column.changeCallback !== undefined? changeInputEvent(formData[column.field],column.changeCallback ,columns,formData): ()=> {}"
              @input="column.inputCallback !== undefined? inputEvent(formData[column.field],column.inputCallback ,columns,formData): ()=> {}"
            />
            <!-- <el-button
              v-if="column.clickInputCallback !== undefined? true: false"
              type="primary"
              icon="el-icon-edit"
              circle
              :style="column.clickInputCallback !== undefined?[{width: '90%'},column.style]:[{width: '100%'},column.style]"
              :disabled="column.alwaysDisabled? true: option.disabled ? column.disabled: false "
              @click="column.clickInputCallback !== undefined? clickInputEvent(formData[column.field],column.clickInputCallback ,columns): ()=> {}"
            /> -->

          </template>

        </el-form-item>
        <!-- ----------------------- -->
      </template>
    </el-form>
    <template>
      <slot v-if="option.footerBtn" :name="option.footerBtn" />
      <span v-else slot="footer" class="dialog-footer">
        <el-button v-if="option.isSetDefault&&option.defaultButtonText" type="primary" @click="setDefault">{{ option.defaultButtonText }}</el-button>
        <el-button type="primary" :loading="option.isSubmitLoading ? true : false" @click="onSubmit('validateForm')">保存</el-button>
        <slot name="footerDelbtn" :formData="formData" />
        <el-button @click="cancel">取消</el-button>
      </span>
    </template>
  </el-dialog>

</template>
<script>
import UploadFile from '../uploadDialog/uploadFile'

export default {
  name: 'TisDialog',
  components: { UploadFile },
  props: {
    // data: {
    //   type: Object,
    //   default: () => {}
    // },
    columns: {
      type: Array,
      default: () => []
    },
    widthLabel: {
      type: String,
      default: () => '140px'
    },
    option: {
      type: Object,
      default: () => {
        return {
          title: 'title',
          width: '50%',
          visible: false, // 是否显示数据
          disabled: true, // 针对是否禁用设置
          isSubmitLoading: true,
          isDialogBodyScroll: false, // 设置body是否可滚动
          inline: true,
          isSetDefault: false,
          marginTop: '5vh',
          defaultButtonText: 'buttonText'
        }
      }
    },
    rules: {
      type: Object,
      default: () => {}
    },
    drag: {
      type: Boolean,
      default: () => true
    },
    inline: {
      type: Boolean,
      default: () => false
    }

  },
  data() {
    return {
      formData: {
      },
      ddlist: [],
      pickerOptions: {
        shortcuts: [{
          text: '长期',
          onClick(picker) {
            console.log('🚀 ~ file: checkMaintenancePlan.vue:239 ~ onClick ~ picker:', picker)
            const start = new Date()
            const end = '9999-12-31'
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  watch: {
    // 'columns': {
    //   deep: true,
    //   immediate: true,
    //   handler(val) {
    //     val.map(item => {
    //       this.$set(this.formData, item.field, item.value || '')
    //     })
    //   }

    // }
  },
  created() {
    this.columns.map(item => {
      this.$set(this.formData, item.field, item.value || '')
    })
  },

  methods: {

    onSubmit(formName) {
      const result = { ...this.formData }
      // todo:这边需要做判断修改

      this.columns.map(item => {
      //  console.log('🚀 ~ file: index.vue ~ line 321 ~ onSubmit ~ item', item)
        if (item.type === 'switch') {
          if (result[item.field] === true) {
            result[item.field] = 1
          } else {
            result[item.field] = 0
          }
        }
        if (item.type === 'uploadFile') {
          const fileList = this.$refs[item.ref][0].getUploadFileList()
          if (fileList && fileList.length > 0) {
            this.formData[item.field] = fileList[0].name
          }
        }
        // 解决输入框输入空格的问题
        // if (item.rules && item.rules.length > 0 && !item.type || item.type === 'textarea') {
        //   result[item.field].trim()
        // }
      })

      // 验证通过
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$emit('submit', result)
        }
        // else {
        //   this.$message.error('请输入验证信息')
        // }
      })
    },
    cancel() {
      this.$refs.validateForm.clearValidate()
      this.option.isSubmitLoading = false
      this.option.visible = false
    },
    setDefault() {
      this.$emit('setDefault')
    },
    getFormData() {
      return this.formData
    },
    setFormData(value) {
      // todo: 验证出错需要优化
      if (typeof value !== 'object') {
        alert('更新数据格式出错')
      }
      // todo: 由于数据系统存储的是0,1 需要对0,1做true和false的转化
      Object.keys(value).forEach(key => {
        this.columns.filter(item => item.field === key)
          .map(item => {
            if (item.type === 'switch') {
              if (value[key] === 1) {
                //
                this.formData[item.field] = true
                // item.value = true
              } else {
                this.formData[item.field] = false
                // item.value = false
              }
            } else {
              this.formData[item.field] = value[key]
              // item.value = value[key]
            }
            if (value.systemFlag === 1) {
              if (item.disabled === false) {
                item.disabled = true
              }
            }
            if (value.type === 1) {
              if (item.disabled === false) {
                item.disabled = true
              }
            }
          })
      })
    },
    setFormProps(value) {
      if (typeof value !== 'object') {
        alert('更新数据格式出错')
      }
      this.columns = this.columns.map(item => {
        if (item.field === value.field) {
          item = { ... value }
        }
      })
    },
    clearFormData() {
      this.columns.map(item => {
        if (item.type !== undefined && item.type === 'switch') {
          this.formData[item.field] = false
          // item.value = false
        } else {
          // item.value = ''
          this.formData[item.field] = null
        }
        // if (item.disabled !== undefined && item.disabled === true) {
        //   item.disabled = false
        // }
      })
    },

    // 获取级联选中的数据
    getCascadeSelectData() {
      return this.$refs.myCascader[0].getCheckedNodes()
    },
    // 失去焦点触发
    visibleChange(visible) {
      if (!visible) {
        this.$emit('visibleChange')
      }
    },
    async  selectChange(value, callback, columns) {
      try {
        await callback(value, columns)
      } catch (err) {

        // this.$message.error(err)
      }
    },
    // 清空select触发
    async clearSelect(value, callback, columns) {
      try {
        await callback(value, columns)
      } catch (err) {

        // this.$message.error(err)
      }
      this.$emit('clearSelect')
    },
    async clickInputEvent(value, callback, columns, formData) {
      try {
        await callback(value, columns, formData)
      } catch (err) {

        // this.$message.error(err)
      }
    },
    async changeInputEvent(value, callback, columns, formData) {
      try {
        await callback(value, columns, formData)
      } catch (err) {

        // this.$message.error(err)
      }
    },
    async inputEvent(value, callback, columns, formData) {
      console.log('🚀 ~ file: index.vue:580 ~ inputEvent ~ value, callback, columns, formData:', value, callback, columns, formData)
      try {
        await callback(value, columns, formData)
      } catch (err) {

        // this.$message.error(err)
      }
    }

  }
}
</script>

<style lang="scss" >
.dialogBox {
  display: flex;
  overflow: hidden;
  .el-dialog {
    margin-top: 9vh !important;
    margin-bottom: 8vh !important;
    overflow: auto;
    .el-dialog__body {
      position: absolute;
      left: 0px;
      top: 54px;
      bottom: 72px;
      right: 0px;
      overflow-y: auto;
      padding-bottom: 0px;
    }
  }
}
.dialog-footer{
  position: absolute;
  left: 0;
  bottom: 20px;
  right: 54px;
  padding: 0;
  z-index: 2;
}
 .el-select-dropdown {
    width: 0 !important;
}
  .uploadLabel {
    width: 154px;
    text-align: right;
    margin-right: 20px;
    font-weight: 700;
  }
</style>
